package com.ddone.service.impl;

import com.ddone.exception.AuthManagerException;
import com.ddone.model.auth.SysUser;
import com.ddone.model.vo.ResultCodeEnum;
import com.ddone.security.AuthUser;
import com.ddone.service.SysUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author ddone
 * @date 2024/3/31-20:44
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        SysUser sysUser = userService.getByUsername(username);
        if (Objects.isNull(sysUser)) {
            throw new AuthManagerException(ResultCodeEnum.ACCOUNT_ERROR);
        }
        if (sysUser.getStatus() == 0) {
            throw new AuthManagerException(ResultCodeEnum.ACCOUNT_STOP);
        }

        // 查询用户拥有的权限
        List<String> userPermsList = userService.getUserBtnPermsByUserId(sysUser.getId());

        // 授权
        List<SimpleGrantedAuthority> authorities = userPermsList.stream()
                .filter(StringUtils::isNotBlank)
                .map(perm -> new SimpleGrantedAuthority(perm.trim()))
                .collect(Collectors.toList());
        return new AuthUser(sysUser, authorities);
    }
}
